import { messages } from 'share/common';
import React from 'react';
import { connect } from 'react-redux';
import menuRoute from 'routes/menuRoute';
import { Form, Input, Switch, message, Icon, Button } from 'antd';
import strategyService from 'containers/budget-setting/budget-organization/budget-strategy/budget-strategy.service';
import 'styles/budget-setting/budget-organization/budget-strategy/new-budget-strategy.scss';
import { LanguageInput } from 'components/template';

const FormItem = Form.Item;

class NewBudgetStrategy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      isEnabled: true,
      budgetOrganizationDetail: menuRoute.getRouteItem('budget-organization-detail', 'key'),    //预算组织详情
      budgetStrategyDetail: menuRoute.getRouteItem('budget-strategy-detail', 'key'),    //预算控制策略详情
      i18n: {}
    };
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({ loading: true });
        const { params: { id } } = this.props;
        const { i18n } = this.state;
        strategyService.newStrategy({ ...values, ...{ organizationId: id, i18n } })
          .then(res => {
            if (res.status === 200) {
              message.success(messages('common.create.success', { name: '' })/*新建成功*/);
              this.context.router.push(this.state.budgetStrategyDetail.url.replace(':id', this.props.params.id)
                .replace(':strategyId', res.data.id));
            }
          })
          .catch((e) => {
            if (e.response) {
              message.error(`${messages('common.create.filed')/*新建失败*/}, ${e.response.data.message}`);
            }
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }
    });
  };

  handleCancel = () => {
    this.context.router.push(this.state.budgetOrganizationDetail.url.replace(':id', this.props.params.id) + '?tab=STRATEGY');
  };

  switchChange = () => {
    this.setState((prevState) => ({
      isEnabled: !prevState.isEnabled
    }))
  };


  handleI18n = (name, value) => {
    let { i18n, controlStrategyName } = this.state;
    i18n.controlStrategyName = value;
    controlStrategyName = name;
    this.setState({ controlStrategyName, i18n });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { isEnabled, controlStrategyName, i18n } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    return (
      <div className="new-budget-strategy">
        <Form onSubmit={this.handleSave} style={{width:'55%',margin:'0 auto'}}>
          <FormItem {...formItemLayout} label={messages('budget-setting.key141'/*预算控制策略代码*/)} hasFeedback>
            {getFieldDecorator('controlStrategyCode', {
              rules: [{
                required: true,
                message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: ''
            })(
              <Input placeholder={messages('common.please.enter')/*请输入*/} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('budget-setting.key142'/*预算控制策略名称*/)} hasFeedback>
            {getFieldDecorator('controlStrategyName', {
              rules: [{
                required: true,
                message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: ''
            })(
              <LanguageInput
                name={controlStrategyName}
                i18nName={i18n.controlStrategyName || null}
                nameChange={this.handleI18n}
                placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('isEnabled', {
              initialValue: isEnabled
            })(
              <div>
                <Switch defaultChecked={true} checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross" />} onChange={this.switchChange}/>
                <span className="enabled-type">
                  {isEnabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
                </span>
              </div>
            )}
          </FormItem>
          <FormItem wrapperCol={{ offset: 7 }}>
              <Button type="primary" htmlType="submit" loading={this.state.loading}>{messages('common.save')/*保存*/}</Button>
              <Button onClick={this.handleCancel} className="btn-cancel">{messages('common.cancel')/*取消*/}</Button>
          </FormItem>
        </Form>
      </div>
    )
  }

}

NewBudgetStrategy.contextTypes={
  router:React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

const WrappedNewBudgetStrategy = Form.create()(NewBudgetStrategy);

export default connect(mapStateToProps)(WrappedNewBudgetStrategy);

